;As good practice I used following tutorials:
;http://rob-rowe.blogspot.com/2011/05/parsing-web-pages-with-clojure-and.html
;http://mmcgrana.github.com/2010/07/develop-deploy-clojure-web-applications.html
;http://techbehindtech.com/2010/09/02/compojure-demystified-with-an-example-part-5/
;;http://mmcgrana.github.com/2010/07/develop-deploy-clojure-web-applications.html

;Informations about displaying multiple checkboxes,regex,recursion, hiccup and ring are found on stackowerflow and google groups
;https://groups.google.com/forum/?fromgroups#!topic/compojure/5Vm8QCQLsaQ
;http://www.reddit.com/r/Clojure/comments/euf90/a_template_app_for_getting_started_with_compojure/
;http://www.lshift.net/blog/2010/02/27/a-simple-web-application-in-clojure-using-ring-and-enlive
;http://gnuvince.wordpress.com/2008/10/31/fetching-web-comics-with-clojure-part-1/

;http://stackoverflow.com/questions/10505229/extracting-string-from-clojure-collections-using-regex
;http://stackoverflow.com/questions/7787741/clojure-recursive-function
;http://stackoverflow.com/questions/10512609/displaying-data-from-two-parallel-sequences-on-web-page-in-compojure
;http://stackoverflow.com/questions/9966348/number-format-exception-in-compojure

;I tried to add CSS, but I was not successfull:
;http://stackoverflow.com/questions/2130448/getting-started-with-css-in-compojure
(ns adder.pages
  (:use compojure.core 
        [hiccup core form page element]
        [adder.PageParser]
        [adder.reorder]
        [adder.dbManagement]
        [adder.image-reader])
  (:require [compojure.handler :as handler])
  (:import [java.io InputStream InputStreamReader BufferedReader]
           [java.net URL HttpURLConnection])); add middleware for params

(defn view-layout2 [& content]
  (html5 [:body content]))

(defn view-layout [& content]
  (html5 		
			[:head				
				[:title "Manga commic book finder"]
    (include-css "resources/public/css/stil.css")
				;;[:link {:href "/public/stil.css" :rel "stylesheet" :type "text/css"}]
    ]
			[:body content ;(include-css "/stil.css")
    ]
    ))


(def all-categories 
  (flatten (map :content (h3+table3 "http://www.mangareader.net/search")))) 

(defn category-checks [selected] 
  (->> all-categories 
       (map (set selected)) 
       (map #(if % 1 0)) 
       (apply str))) 


(defn view-input [] 
  (view-layout 
    [:h2 "Find"] 
    (form-to [:post "/"]
             [:div.categories ;{:width "100px"}
      (interleave         
        (for [category all-categories] 
        (check-box "categories[]" false  category))                
      (for [category all-categories]
        (label "name" category)))]
      [:br] [:br]
      (text-field {:placeholder "insert manga name"} :a) [:br] 
      (submit-button "Find")
      [:br]
      (link-to "localhost:3000/listseries" "See all franchises")
      [:br]
      (link-to "localhost:3000/listcommics" "See all commics")
      )))

(defn create-manga-url [selected-cats a]   
  (str "http://www.mangareader.net/search/?w=" a "&rd=0&status=0&order=0&genre=" 
       (category-checks selected-cats)))


(defn manga-vec [categories a]
           (vec (let [manga-url (create-manga-url categories a)
                      manga-names (print-manga-name-content manga-url)]
                  (mapper-gen4 manga-names
                   (get-image-content manga-url) 
                   (get-manga-rating4 manga-names)
                   (get-all-reading-links manga-url)
                   (get-search-URLS manga-names)
                   ))) )

(defn view-output2 [categories a]    
  (view-layout
    [:h2 "Search results"]
    [:form {:method "post" :action "/"}               
      (interleave
        (for [manga (manga-vec categories a)]        
        (label :manga_name (:name manga))) 
        
        (for [manga-name (manga-vec categories a)]        
        [:br])         
                      
        (for [manga-read-link (manga-vec categories a)]
          (link-to (:download-link manga-read-link) "Download it here!"))
        
        (for [manga-read-link (manga-vec categories a)]
          (link-to (:read-link manga-read-link) "Read it here!"))
        
        (for [manga-image (manga-vec categories a)]
           [:img {:id "image_manga" :src (:image manga-image)}])
        
        (for [manga-rank (manga-vec categories a)]
          (if (not (= (:rank manga-rank) 10000000)) (:rank manga-rank) "Not Ranked!")
           )
        (for [manga (manga-vec categories a)]
          [:br]))]))

;series cruds

(defn view-franchises "view all available franchises" []
  (html5 		
			[:head				
				[:title "Franchise commic book collection"]
    ;(include-css "/css/stil.css")
    ]
			[:body {:style "background-color: #ccd9c8"}
    (str "<table border=1px bgcolor= white>"
         ( apply str (seq (for [franchise (list-series)]
           (str "<tr>" 
           "<td>"(:series_publisher franchise) "</td>"
           "<td>"(:series_name franchise) "</td>"           
          ;"<td>" (link-to (:read-link ) "See it here!") "</td>" ;
           "<td>" "<a href=" (str "localhost:3000/listcommicsfran/" (:series_id franchise)) ">" "See all saved commics from this franchise here!" "</a>" "</td>"
           "<td>" "<a href=" (str "localhost:3000/editfranchise/" (:series_id franchise)) ">" "Edit franchise" "</a>" "</td>"
           "<td>" "<a href=" (str "localhost:3000/deletefranchise/" (:series_id franchise)) ">" "Delete franchise" "</a>" "</td>"
           ;"<td>" "<a href=" (str "localhost:3000/addnewfranchise") ">" "Add new franchise" "</a>" "</td>"
           "</tr>"            
           )
         )))
         "<tr>"
           "<td>" "<a href=" (str "localhost:3000/addnewfranchise") ">" "Add new franchise" "</a>" "</td>"
           "</tr>"
         "</table>")]))

(defn save-franchise [] 
  (view-layout 
    [:h2 "Add new franchise"] 
    (form-to [:post "/addnewfranchise"]
            
      (label "lblseriesName" "Franchise Name")
      (text-field  :txtname) [:br] 
      
      (label "lblPublisher" "Writter name")
      (text-field  :txtwrname) [:br]
      
      (submit-button "Save"))))

(defn update-franchise [sid] 
  (view-layout 
    [:h2 "Update franchise"] 
    (form-to [:put (format "/editfranchise/%s" sid)];editfranchise
            
      (label "lblseriesName" "Franchise Name")
      (text-field  :txtname (first (map :series_name (list-one-series sid)))) [:br] 
      
      (label "lblPublisher" "Writter name")
      (text-field  :txtwrname (first (map :series_publisher (list-one-series sid)))) [:br]
      
      (submit-button "Update"))))

(defn delete-franchise [sid] 
  (view-layout 
    [:h2 "Are you sure you want to delete?"] 
    (form-to [:delete (format "/deletefranchise/%s" sid)];deletefranchise
            
      (label "lblseriesName" "Franchise Name")
      (text-field  :txtname (first (map :series_name (list-one-series sid)))) [:br] 
      
      (label "lblPublisher" "Writter name")
      (text-field  :txtwrname (first (map :series_publisher (list-one-series sid)))) [:br]
      
      (submit-button "Delete"))))
;end

;;commic CRUDS

(defn view-commics "view all available commics" []   
  (html5 		
			[:head				
				[:title "Franchise commic book collection"]
    ;(include-css "/css/stil.css")
    ]
			[:body {:style "background-color: #ccd9c8"}
    (str "<table border=1px bgcolor= white>"
         ( apply str (seq (for [commic (list-comics)]
           (str "<tr>" 
           "<td>"(:name commic) "</td>"
           "<td>"(:rank commic) "</td>"
           "<td>"(:writter commic) "</td>"
           "<td>" (str "<a href=localhost:3000/viewimage/" (:id commic) ">"  "Check it here!" "</a>") "</td>"
           ;"<td>" (str "<a href=localhost:3000/onecommic >"  "Add new here!" "</a>") "</td>"
           "<td>" (str "<a href=localhost:3000/onecommic/" (:id commic) ">"  "Update it here!" "</a>") "</td>"
           "<td>" (str "<a href=localhost:3000/deletecommic/" (:id  commic) ">"  "Delete it here!" "</a>") "</td>"
           "</tr>"))))
         "<tr>" 
         "<td>" (str "<a href=localhost:3000/onecommic >"  "Add new here!" "</a>") 
         "</td>" 
         "</tr>" 
         "</table>")]))


(defn view-commics-from-one-franchise "view all available commics from one franchise" [sid]   
  (html5 		
			[:head				
				[:title "Franchise commic book collection"]
    ;(include-css "/css/stil.css")
    ]
			[:body {:style "background-color: #ccd9c8"}
    (str "<table border=1px bgcolor= white>"
         ( apply str (seq (for [commic (list-all-comics-from-serie sid)]
           (str "<tr>" 
           "<td>"(:name commic) "</td>"
           "<td>"(:rank commic) "</td>"
           "<td>"(:writter commic) "</td>"
           "<td>" (str "<a href=localhost:3000/viewimage/" (:id commic) ">"  "Check it here!" "</a>") "</td>"
           ;"<td>" (str "<a href=localhost:3000/onecommic >"  "Add new here!" "</a>") "</td>"
           "<td>" (str "<a href=localhost:3000/onecommic/" (:id commic) ">"  "Update it here!" "</a>") "</td>"
           "<td>" (str "<a href=localhost:3000/deletecommic/" (:id  commic) ">"  "Delete it here!" "</a>") "</td>"
           "</tr>")
         ))) "<tr>" "<td>" (str "<a href=localhost:3000/addnewcommictofran/" sid ">"  "Add new here!" "</a>") "</td>" "</tr>"
         "</table>")]))

(defn view-commic-input-update [cid] 
  (view-layout 
    [:h2 "Update commic"] 
    (form-to [:put (format "/onecommic/%s" cid)]
            
      (label "comname" "Commic book name")
      (text-field  :txtname (first (map :name (list-one-comic cid)))) [:br] ;(first (:name (list-one-comic cid)))
      
      (label "wrname" "Writter name")
      (text-field  :txtwrname (first (map :writter (list-one-comic cid)))) [:br] 
      (label "lbllocation" "File location")
      (text-field :txtlocation (first (map :location (list-one-comic cid))))[:br]
      
      (label "rank" "Rank")
      (text-field  :txtrank  (first (map :rank (list-one-comic cid))))
      [:br] 
      (submit-button "Update"))))

(defn view-commic-input-delete [cid] 
  (view-layout 
    [:h2 "Delete commic"] 
    (form-to [:delete (format "/deletecommic/%s" cid)]
            
      (label "comname" "Commic book name")
      (text-field  :txtname (first (map :name (list-one-comic cid)))) [:br] 
      
      (label "wrname" "Writter name")
      (text-field  :txtwrname (first (map :writter (list-one-comic cid)))) [:br] 
      (label "location" "File location")
      (text-field :txtlocation (first (map :location (list-one-comic cid))))[:br]      
      (label "rank" "Rank")
      (text-field  :txtrank  (first (map :rank (list-one-comic cid))))
      [:br] 
      (submit-button "Delete"))))

(defn view-commic-input [] 
  (view-layout 
    [:h2 "Add new commic"] 
    (form-to [:post "/onecommic" ]
            
      (label "comname" "Commic book name")
      (text-field  :txtname) [:br] 
      
      (label "wrname" "Writter name")
      (text-field  :txtwrname) [:br] 
      (label "location" "File location")
      (text-field :txtlocation)[:br]
      
      (label "rank" "Rank")
      (text-field  :txtrank)[:br]
      (submit-button "Save"))))

(defn view-commic-input-in-franchise [sid] 
  (view-layout 
    [:h2 "Add new commic"] 
    (form-to [:post (format "/addnewcommictofran/%s" sid)]
            
      (label "comname" "Commic book name")
      (text-field  :txtname) [:br] 
      
      (label "wrname" "Writter name")
      (text-field  :txtwrname) [:br] 
      (label "location" "File location")
      (text-field :txtlocation)[:br]
      
      (label "rank" "Rank")
      (text-field  :txtrank)[:br]
      (submit-button "Save"))))
;;end

(defn view-image [loc] "Open commic as an image"
  (html5 [:head				
				[:title "Manage selected franchise"]]
         [:body] (str (open-image2 loc))))

(defroutes main-routes            
   (GET "/" []
      (view-input))
  
  (POST "/" [categories a] 
  (view-output2 categories a))
  
  
  ;;commic
  (GET "/listcommics" []
        (view-commics))
  
  (GET "/onecommic/:cid" [cid] (view-commic-input-update cid))
  (PUT "/onecommic/:cid" [cid txtname txtwrname txtlocation txtrank] (update-manga (read-string cid) {:name txtname :writter txtwrname :location txtlocation :rank txtrank}))
  
  (GET "/addnewcommictofran/:sid" [sid] (view-commic-input-in-franchise sid))
  (POST "/addnewcommictofran/:sid" [sid txtname txtwrname txtlocation txtrank]
        (insert-manga txtname txtwrname txtlocation txtrank (read-string sid)))
  
  (GET "/onecommic" [] (view-commic-input))
  (POST "/onecommic" [txtname txtwrname txtlocation txtrank]
        (insert-manga txtname txtwrname txtlocation txtrank 100000000))
  
  (GET "/deletecommic/:cid" [cid] (view-commic-input-delete cid))
  (DELETE "/deletecommic/:cid" [cid] (delete-manga cid))
  
  (GET "/listcommicsfran/:sid" [sid]
        (view-commics-from-one-franchise sid))
  ;;end
  
  ;;franchise
  (GET "/listseries" []
        (view-franchises))
  
  (GET "/addnewfranchise" [] (save-franchise))
  (POST "/addnewfranchise" [txtname txtwrname] (insert-serie txtname txtwrname))
  
  (GET "/editfranchise/:sid" [sid] (update-franchise sid));editfranchise
  (PUT "/editfranchise/:sid" [sid txtname txtwrname] (update-serie (read-string sid) {:series_name txtname :series_publisher txtwrname}))
  
  (GET "/deletefranchise/:sid" [sid] (delete-franchise sid))
  (DELETE "/deletefranchise/:sid" [sid] (delete-series sid))
  ;;end
  
  (GET "/viewimage/:cid" [cid] (view-image (load-image-path cid)));podesi da otvara istu stranicu kao i edit stripa, a samo jos da u pozadini pozove otvaranje slike
  
  
  
  )
   

(def app (handler/site main-routes)) ; wrap the params to allow destructuring to work